<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span class="title">修改验收标准</span>
        <div class="btn-wrap">
          <!-- <el-button size="middle" type="text" @click="handleAssociateProduct"
            >关联商品</el-button
          >
          <el-divider direction="vertical"></el-divider> -->
          <el-button size="middle" type="text" :loading="exportBtnLoading" @click="exportTable"
            >模板导出</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-upload
            class="import-file"
            ref="bacthUpload"
            action="sysback/checksd/finish/saveFinishToPage"
            accept=".xls, .xlsx"
            :before-upload="beforeFileUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :show-file-list="false"
          >
            <el-button size="middle" type="text" :loading="importBtnLoading"
              >模板导入</el-button
            >
          </el-upload>
          <el-divider direction="vertical"></el-divider>
          <el-button
            size="middle"
            type="text"
            :loading="saveBtnLoading"
            @click="handleSubmit"
            >提交</el-button
          >
        </div>
      </div>
      <div>
        <Umy-table
          :loading="tableLoading"
          :data-source="baseTableData"
          :columns="tableColumns"
          :isShowSelection="true"
          @handleCancelSelect="handleCancelSelect"
          @handleSelectionChange="handleSelectionChange"
        />
      </div>
    </el-card>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import UmyTable from '@/components/UmyTable';
export default {
  mixins: [],
  components: {
    UmyTable,
  },
  data () {
    return {
      exportBtnLoading: false,
      importBtnLoading: false,
      tableLoading: false,
      saveBtnLoading: false,
      baseTableData: [],
      skuNoList: [],
      uuids: '',
      tableColumns: [
        {
          title: '分类',
          key: 'categoryPath',
          width: 180
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          align: 'center',
          width: 80
        },
        {
          title: 'SKU编码',
          key: 'skuNo',
          align: 'center',
          width: 80
        },
        {
          title: '商品名称',
          key: 'productName',
          align: 'center',
          width: 140
        },
        {
          title: '品牌',
          key: 'brandName',
          align: 'center',
          width: 100
        },
        {
          title: '规格',
          key: 'specDetailStr',
          align: 'center',
          width: 100
        },
        {
          title: '验收频率',
          required: true,
          align: 'center',
          width: 120,
          children: [
            {
              title: '原值',
              align: 'center',
              key: 'checkFrequency',
              width: 90
            },
            {
              title: '现值',
              align: 'center',
              key: 'checkFrequencyUpdate',
              type: 'inputNumPrecision',
              precision: 0,
              minVal: 1,
              width: 150
            }
          ]
        },
        {
          title: '验收时间',
          required: true,
          align: 'center',
          width: 120,
          children: [
            {
              title: '原值',
              align: 'center',
              key: 'checkTime',
              width: 120
            },
            {
              title: '现值',
              align: 'center',
              key: 'checkTimeUpdate',
              type: 'select',
              options: [
                {
                  value: '入库前',
                  label: '入库前'
                },
                {
                  value: '入库后',
                  label: '入库后'
                }
              ],
            }
          ]
        }
      ],
      apiObj: {
        // 点击批量维护/查看/编辑，进入维护页面（品类、商品状态必须相同）
        getListByUuids: {
          url: '/sysback/checkstandarddetail/getListByUuids', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 查看单据信息
        queryRecordExistBySku: {
          url: '/sysback/product/update/record/queryRecordExistBySku', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 保存
        saveBasicInfo: {
          url: '/sysback/checksd/finish/commitFinish', // 接口地址
          type: 'post' // 接口请求类型
        }
      }
    };
  },
  created () {
    this.uuids = this.$route.query.uuids;
    this.initData();
  },
  methods: {
    initData () {
      this.tableLoading = true;
      ApiRequest(
        this.apiObj.getListByUuids.url + '?uuids=' + this.uuids,
        this.apiObj.getListByUuids.type,
        {},
        false
      ).then((res) => {
        this.tableLoading = false;
        if (res.retStatus === '1') {
          let reData = res.retData;
          this.initView(reData);
        }
      });
    },
    initView (reData) {
      this.baseTableData = [];
      reData.forEach((element, oneIndex) => {
        let currentRow = {
          uuid: element.uuid,
          operationNumber: element.operationNumber,
          createOpeTime: element.createOpeTime,
          skuNo: element.skuNo,
          specDetailStr: element.specDetailStr,
          spuNo: element.spuNo,
          productUuid: element.productUuid,
          productName: element.productName,
          categoryPath: element.categoryPath,
          brandName: element.brandName,
          checkTime: element.checkTime,
          checkTimeUpdate: element.checkTimeUpdate,
          checkFrequency: element.checkFrequency,
          checkFrequencyUpdate: element.checkFrequencyUpdate,
          productAddState: element.productAddState,
          categoryName: element.categoryName,
          detailList: element.detailList
        }
        element.detailList.forEach((item, index) => {
          this.pushItem(oneIndex, currentRow, item, index);
        });
        this.baseTableData.push(currentRow);
      });
      /* this.tableColumns.push({
        title: '操作',
        key: 'action',
        align: 'center',
        fixed: 'right',
        width: 90
      }); */
    },
    handleAssociateProduct () {
      console.log('关联商品')
    },
    handleSelectionChange (row) {
      this.skuNoList = [];
      row.forEach((element) => {
        this.skuNoList.push(element.skuNo);
      });
    },
    // 删除
    handleCancelSelect (obj) {
      const { index } = obj;
      this.baseTableData.splice(index, 1);
    },
    // 将行内动态列的信息，平铺到行
    pushItem (oneIndex, curRow, innerEle, index) {
      // 验收次数
      curRow['checkCount' + index] = innerEle.checkCount;
      curRow['checkCountUpdate' + index] = innerEle.checkCountUpdate;
      // 标准值
      curRow['standardValue' + index] = innerEle.standardValue;
      curRow['standardValueUpdate' + index] = innerEle.standardValueUpdate;
      // 上差值
      curRow['upDiffValue' + index] = innerEle.upDiffValue;
      curRow['upDiffValueUpdate' + index] = innerEle.upDiffValueUpdate;
      // 下差值
      curRow['downDiffValue' + index] = innerEle.downDiffValue;
      curRow['downDiffValueUpdate' + index] = innerEle.downDiffValueUpdate;
      // 验收方法
      curRow['checkMethod' + index] = innerEle.checkMethod;
      curRow['checkMethodUpdate' + index] = innerEle.checkMethodUpdate;
      // 1数字5个列可填，2文本3个列可填
      curRow['checkItemType' + index] = innerEle.checkItemType;

      // 表头，遍历第1行的动态列时，才追加到表头
      if (oneIndex === 0) {
        if (innerEle.checkItemType !== '2') {
          this.tableColumns.push({
            title: innerEle.checkItemName,
            required: innerEle.isNeed === '1',
            key: innerEle.checkItemUuid,
            width: 150,
            align: 'center',
            children: [
              {
                title: '验收次数原值',
                align: 'center',
                key: 'checkCount' + index,
              },
              {
                title: '验收次数现值',
                align: 'center',
                key: 'checkCountUpdate' + index,
                type: 'inputNum',
                minVal: 1,
                width: 150
              },
              {
                title: '标准值原值',
                align: 'center',
                key: 'standardValue' + index,
              },
              {
                title: '标准值现值',
                align: 'center',
                key: 'standardValueUpdate' + index,
                type: 'input',
                width: 150
              },
              {
                title: '上差值原值',
                align: 'center',
                key: 'upDiffValue' + index,
              },
              {
                title: '上差值现值',
                align: 'center',
                key: 'upDiffValueUpdate' + index,
                type: 'inputNum',
                width: 150
              },
              {
                title: '下差值原值',
                align: 'center',
                key: 'downDiffValue' + index,
              },
              {
                title: '下差值现值',
                align: 'center',
                key: 'downDiffValueUpdate' + index,
                type: 'inputNum',
                width: 150
              },
              {
                title: '验收方法原值',
                align: 'center',
                key: 'checkMethod' + index,
              },
              {
                title: '验收方法现值',
                align: 'center',
                key: 'checkMethodUpdate' + index,
                type: 'input',
                width: 150
              },
            ]
          });
        } else {
          this.tableColumns.push({
            title: innerEle.checkItemName,
            required: innerEle.isNeed === '1',
            key: innerEle.checkItemUuid,
            width: 150,
            align: 'center',
            children: [
              {
                title: '验收次数原值',
                align: 'center',
                key: 'checkCount' + index,
              },
              {
                title: '验收次数现值',
                align: 'center',
                key: 'checkCountUpdate' + index,
                type: 'inputNum',
                minVal: 1,
                width: 150
              },
              {
                title: '标准值原值',
                align: 'center',
                key: 'standardValue' + index,
              },
              {
                title: '标准值现值',
                align: 'center',
                key: 'standardValueUpdate' + index,
                type: 'input',
                width: 150
              },
              {
                title: '验收方法原值',
                align: 'center',
                key: 'checkMethod' + index,
              },
              {
                title: '验收方法现值',
                align: 'center',
                key: 'checkMethodUpdate' + index,
                type: 'input',
                width: 150
              },
            ]
          });
        }
      }
    },
    // 保存
    handleSubmit () {
      let submitList = [];
      let hasEmptyVal = this.baseTableData.some((item) => (!item.checkFrequencyUpdate || !item.checkTimeUpdate))
      if (hasEmptyVal) {
        return this.$Message.error('确保列表内容不能为空');
      }
      this.baseTableData.forEach((element) => {
        element.detailList.forEach((item, innerI) => {
          item.checkCountUpdate = element['checkCountUpdate' + innerI];
          item.standardValueUpdate = element['standardValueUpdate' + innerI];
          item.upDiffValueUpdate = element['upDiffValueUpdate' + innerI];
          item.downDiffValueUpdate = element['downDiffValueUpdate' + innerI];
          item.checkMethodUpdate = element['checkMethodUpdate' + innerI];
        });
        submitList.push({
          checkFrequencyUpdate: element.checkFrequencyUpdate,
          checkTimeUpdate: element.checkTimeUpdate,
          skuNo: element.skuNo,
          spuNo: element.spuNo,
          productUuid: element.productUuid,
          itemList: element.detailList
        });
      });
      this.saveBtnLoading = true;
      ApiRequest(
        this.apiObj.saveBasicInfo.url,
        this.apiObj.saveBasicInfo.type,
        submitList,
        false
      ).then((res) => {
        this.saveBtnLoading = false;
        if (res.retStatus === '1') {
          this.$Message.success('提交成功');
          this.$router.go(-1);
        }
      });
    },
    // 导出表格
    exportTable () {
      if (this.skuNoList.length === 0) {
        return this.$Message.error('请先勾选要导出的数据');
      } else {
        window.location.href =
          this.exportBaseURL +
          '/sysback/checksd/finish/exportPageToExcelGet?skuNoList=' +
          this.skuNoList.join(',');
      }
    },
    // 上传之前
    beforeFileUpload () {},
    // 上传成功
    uploadSuccess (file) {
      if (file.retStatus === '1') {
        // 如果上传成功,并且接口返回成功,对表格进行赋值操作.
        this.initView(file.retData);
      } else {
        // 如果接口返回失败,就打印失败信息
        this.$Message.success(file.retMessage);
      }
    },
    // 上传失败
    uploadError () {
      this.$Message.error('上传失败');
    },
    // 返回操作
    backButton () {
      this.$router.go(-1);
    }
  }
};
</script>
<style lang="less" scoped>
.btn-wrap {
  float: right;
  .import-file {
    display: inline;
  }
}
.card-header {
  .title {
    font-size: 16px;
  }
}
</style>
